package com.apples.hexviewer2;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.BackgroundColorSpan;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.apples.hexviewer2.databinding.ActivityFunBinding;

import java.util.ArrayList;
import java.util.List;

public class FunActivity extends AppCompatActivity {

    private static final int PERMISSION_REQUEST_CODE = 1;

    private ActivityFunBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityFunBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (!checkPermission()) {
            requestPermission();
        }
        initData();
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String xx = preferences.getString("hex_viewer_open_path", null);
        if (xx == null || xx.isEmpty()) {
            String parent1 = Environment.getExternalStorageDirectory().getPath();
            SharedPreferences.Editor edit = preferences.edit();
            edit.putString("hex_viewer_open_path", parent1);
            edit.apply();
        }

//        //Test "/storage/emulated/0/cnlaunch/iSmartEV/988170005398/DIAGNOSTIC/"
//        String parent1 = "/storage/emulated/0/cnlaunch/iSmartEV/988170005398/DIAGNOSTIC/";
//        SharedPreferences.Editor edit = preferences.edit();
//        edit.putString("hex_viewer_open_path", parent1);
//        edit.apply();
//
//        String paths = preferences.getString("hex_viewer_recently_path", null);
//        System.out.println("============================================================");
//        System.out.println(paths);
//        //Test
    }

    private void initData() {
        binding.buttonOpenFile.setOnClickListener(v -> {
            Intent intent = new Intent(this, OneActivity.class);
            startActivity(intent);
        });
        binding.buttonCompareOpenFile.setOnClickListener(v -> {
            Intent intent = new Intent(this, TwoActivity.class);
            startActivity(intent);
        });
        binding.buttonRecentlyOpen.setOnClickListener(v -> {
            Intent intent = new Intent(this, ThreeActivity.class);
            startActivity(intent);
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission granted
                System.out.println("HexViewer2 Permission granted");
            } else {
                showPermissionDeniedDialog();
            }
        }
    }

    private void showPermissionDeniedDialog() {
        new AlertDialog.Builder(this)
                .setCancelable(false)
                .setTitle(R.string.label_tip_msg9)
                .setMessage(R.string.label_tip_msg11)
                .setPositiveButton(R.string.label_tip_msg10, (dialogInterface, i) -> {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", getPackageName(), null);
                    intent.setData(uri);
                    startActivity(intent);
                })
                .setNegativeButton(R.string.menu_exit_hex, (dialogInterface, i) -> finish())
                .create()
                .show();
    }

    private boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int result2 = ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE);
        return result == PackageManager.PERMISSION_GRANTED
                && result2 == PackageManager.PERMISSION_GRANTED;
    }

    private void requestPermission() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
    }

    public static void showTip(Context context, String tip) {
        Toast toast = Toast.makeText(context, tip, Toast.LENGTH_LONG);
        View view = toast.getView();
        TextView view2 = view.findViewById(android.R.id.message);
        view2.setTextSize(24);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    public static void showTip2(Context context, String tip) {
        new AlertDialog.Builder(context)
                .setCancelable(false)
                .setTitle(R.string.label_tip_msg12)
                .setMessage(tip)
                .setPositiveButton(R.string.tip_alert_ok_hex, null)
                .create()
                .show();
    }

    // 设置选中文字并应用样式
    public static void selectText(TextView textView, int start, int end, int... args) {
        if (args.length == 0)
            clearSelection(textView);
        if (start == -1 || end == -1) return;
        SpannableStringBuilder spannable = SpannableStringBuilder.valueOf(textView.getText());
        BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(Color.parseColor("#ff4285f4"));
        spannable.setSpan(backgroundColorSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(spannable);
    }

    // 清除选中文字的样式
    public static void clearSelection(TextView textView) {
        SpannableStringBuilder spannable = SpannableStringBuilder.valueOf(textView.getText());
        BackgroundColorSpan[] backgroundColorSpans = spannable.getSpans(0, spannable.length(), BackgroundColorSpan.class);
        if (backgroundColorSpans != null) {
            for (BackgroundColorSpan span : backgroundColorSpans)
                spannable.removeSpan(span);
            textView.setText(spannable);
        } else {
            textView.setText(textView.getText().toString());
        }
    }

    public static void showSoftKeyboard(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        view.requestFocus();
        inputMethodManager.showSoftInput(view, 0);
    }

    public static void hideSoftKeyboard(Activity activity) {
        View focusedView = activity.getCurrentFocus();
        if (focusedView != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(focusedView.getWindowToken(), 0);
        }
    }

    public static byte[] convertListToByteArray(List<Byte> byteList) {
        byte[] byteArray = new byte[byteList.size()];
        for (int i = 0; i < byteList.size(); i++) {
            byteArray[i] = byteList.get(i);
        }
        return byteArray;
    }

    public static List<Byte> convertByteArrayToList(byte[] byteArray) {
        List<Byte> byteList = new ArrayList<>();
        for (byte b : byteArray) {
            byteList.add(b);
        }
        return byteList;
    }
}